package org.zgr.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @Author: 郑国荣
 * @Date: 2024-01-05-13:04
 * @Description:
 */
@Configuration
public class GatewayFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 在请求头加入gateway key
        ServerHttpRequest request = exchange.getRequest(); // 获取请求
        PathContainer pathContainer = request.getPath().pathWithinApplication();  // 获取请求路径
        System.out.println("请求路径：" + pathContainer.value());
        // 添加gatewayKey，防止下游接口直接被访问
        ServerHttpRequest.Builder mutate = request.mutate(); // 构建请求
        mutate.header("gatewayKey", "key");
        // 获取请求ip
        String ip = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
        if (pathContainer.value().contains("user")) {
            System.out.println("请求ip：" + ip);
            System.out.println("请求UserService");
        }
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
